package com.beyondzy.commmon.util;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * @author beyondzy
 * @date 2024/11/7
 **/
@Component
public class EmailSendUtil {
    @Autowired
    private JavaMailSenderImpl MailSender; //定制"短信发送"的API类: JavaMailSenderImpl

    // @Value()注解 : 将application.properties : 配置文件中的 “属性值” 注入到下面的from属性中,给该属性充当"属性值"
    @Value("${spring.mail.username}")
    private String from; //发件人地址

    /**
     * @param to      收件人地址
     * @param subject 邮箱标题
     * @param text    邮箱内容
     */
    public void sendSimpleEmail(String to,String subject,String text) {
        //定制纯文本邮信息的 SimpleMailMessage对象
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from); //设置"发件人"地址
        message.setTo(to); //设置"收件人"地址
        message.setSubject(subject); //设置"邮件标题"
        message.setText(text); //设置"邮件发送文本"

        try {
            //发送邮件
            MailSender.send(message);
        }catch (MailException e){
            System.out.println("纯文本邮件发送失败 "+e.getMessage());
        }
    }
    public void sendTemplateEmail(String to,String subject,String content) {
        //定制"复杂邮件信息类" : MimeMessage类
        MimeMessage message = MailSender.createMimeMessage();
        try {
            //使用 MimeMessageHelper 帮助类，并设置multipart多部件使用为true
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from); //设置"发件人地址"
            helper.setTo(to); //设置"收件人"地址
            helper.setSubject(subject); //设置"邮件"的标题
            helper.setText(content,true); //设置"邮件"的文本内容 --其中包含"模板邮件"的内容

            //发送邮件
            MailSender.send(message);
            System.out.println("模板邮件发送成功!");

        } catch (MessagingException e) {
            System.out.println("模板邮件发送失败" + e.getMessage());
            e.printStackTrace();
        }

    }
}
